package com.cs.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cs.entity.PSExcelVo;
import com.cs.entity.SystemPrice;
import com.cs.entity.SystemPriceItem;
import com.cs.mapper.SystemPriceMapper;
import com.cs.service.ISystemPriceItemService;
import com.cs.service.ISystemPriceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 运费价格体系  服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2022-06-07 06:17:08
 */
@Service
public class SystemPriceServiceImpl extends ServiceImpl<SystemPriceMapper, SystemPrice> implements ISystemPriceService {
    @Autowired
    private ISystemPriceItemService systemPriceItemService;
    @Override
    public void exportPsData(HttpServletResponse response, int i) throws IOException {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("体系模板", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //查询数据库
        List<SystemPrice> list = this.list(new QueryWrapper<SystemPrice>().eq("site_id", 29));
        List<PSExcelVo> psExcelVos = new ArrayList<>();
        for (SystemPrice systemPrice : list) {
            List<SystemPriceItem> list1 = systemPriceItemService.list(new QueryWrapper<SystemPriceItem>().eq("system_price_id", systemPrice.getId()));
            if (list1.size() == 0) {
                PSExcelVo psExcelVo = new PSExcelVo();
                psExcelVo.setName(systemPrice.getName());
                psExcelVo.setMinPrice(systemPrice.getMinPrice()/100);
                psExcelVos.add(psExcelVo);
            } else {
                for (SystemPriceItem systemPriceItem : list1) {
                    PSExcelVo psExcelVo = new PSExcelVo();
                    psExcelVo.setName(systemPrice.getName());
                    psExcelVo.setMinPrice(systemPrice.getMinPrice()/100);
                    if (systemPriceItem.getType() == 1) {
                        psExcelVo.setPrice1(systemPriceItem.getPrice()/100);
                        psExcelVo.setValue1(systemPriceItem.getValue());
                    } else {
                        psExcelVo.setPrice2(systemPriceItem.getPrice()/100);
                        psExcelVo.setValue2(systemPriceItem.getValue());
                    }
                    psExcelVos.add(psExcelVo);
                }
            }
        }

        EasyExcel.write(response.getOutputStream(), PSExcelVo.class)
                .sheet("Sheet1")
                .doWrite(psExcelVos);
    }
}
